﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.PrintService;
using CoreShop.Services;
using FastMember;
using NPOI.HSSF.Record;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Windows.Forms;

namespace CoreShop.App
{
    public partial class frmPrintTemplate : UIForm
    {
        int typeId = 0;
        public frmPrintTemplate()
        {
            InitializeComponent();
        }

        private void LoadPrintScheme()
        {
            var where = Expressionable.Create<corecmsprintbilltype>();
            where = where.And(p => p.id > 0);

            //如果不启用厨房打印，不显示厨房打印方案名称
            if (!AppConstVars.systemsetup.isKitchen)
                where = where.And(p => p.tagId != (int)GlobalEnumVars.PrintbillTypeTag.Kitchen);
            List<corecmsprintbilltype> lstSource = new corecmsprintbilltypeServices().AsQueryable()
                .Where(where.ToExpression()).OrderBy(p => p.tagId).ToList();

            tvTemplate.Nodes.Clear();
            TreeNode treeNode = new TreeNode("全部模板");
            treeNode.Tag = "0";
            tvTemplate.Nodes.Add(treeNode);
            foreach (var item in lstSource)
            {
                TreeNode treeNode10 = new TreeNode(item.name);
                treeNode10.Tag = item.id.ToString();
                treeNode.Nodes.Add(treeNode10);
            }
            tvTemplate.Nodes[0].Expand();
            GetTemplatDetail(typeId);
        }

        private void FDishPinterSetup_Shown(object sender, System.EventArgs e)
        {
        }

        private void GetTemplatDetail(int typeId)
        {
            //查询所有打印格式模板
            var template = new corecmsprintbilltemplateServices().QueryAsync(typeId, AppConstVars.systemsetup);
            laySchemeDetail.Visible = false;
            laySchemeDetail.Clear();
            foreach (var info in template)
            {                  
                if (info.billtypeId == (int)GlobalEnumVars.PrintbillType.Label) 
                    info.paperType = (int)GlobalEnumVars.paperType.custom;//标签纸张大小显示为显示自定义
                UIDishPrintbillTemplateItem item = new UIDishPrintbillTemplateItem(info, btnSaveTemplate.Visible);
                item.ModifyItemClick += Detail_OnModifyItemClick;
                item.CopyItemClick += Detail_OnCopyItemClick;
                item.ModifyReportClick += Detail_OnModifyReportClick;
                item.DeleteItemClick += Detail_OnDeleteItemClick;
                item.SaveItemClick += Detail_OnSaveItemClick;
                laySchemeDetail.Add(item);
            }
            laySchemeDetail.Visible = true;
        }

        private void Detail_OnCopyItemClick(object sender, System.EventArgs e)
        {
            try
            {
                corecmsprintbilltemplate printbilltemplate = (corecmsprintbilltemplate)sender;
                if (printbilltemplate == null)
                {
                    UIMessageBox.Show("模板不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                GetPrintTemplatePool(printbilltemplate);                
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错:", UIStyle.Orange, UIMessageBoxButtons.OK);
            }
        }

        private void Detail_OnDeleteItemClick(object sender, System.EventArgs e)
        {
            try
            {
                if (!ShowAskDialog("确定要删除所选择打印格式模板吗？")) return;
                corecmsprintbilltemplate item = (corecmsprintbilltemplate)sender;

                var isUsed = new corecmsprintschemedetailServices().AsQueryable().Where(p => p.templateId == item.id).Any();
                if (isUsed)
                {
                    UIMessageBox.Show("该模板已被打印机引用，不能删除", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                bool bResult = new corecmsprintbilltemplateServices().DeleteById(item.id);
                if (bResult)
                {
                    List<corecmsprintschemedetail> detailList = new corecmsprintschemedetailServices().SelectByTemplateId(item.id);
                    if (detailList.Count > 0) bResult = new corecmsprintschemedetailServices().Delete(p => p.templateId == item.id);
                }
                if (!bResult)
                {
                    UIMessageBox.Show("删除失败", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                LoadPrintScheme();
                UIMessageBox.Show("删除成功", "系统提示", UIStyle.Blue, UIMessageBoxButtons.OK);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void Detail_OnSaveItemClick(object sender, System.EventArgs e)
        {
            try
            {
                if (!ShowAskDialog("确定要保存所选择打印格式到远程模板库吗？")) return;
                corecmsprintbilltemplate item = (corecmsprintbilltemplate)sender;

                var list = new corecmsprintbilltemplateServices().AsQueryable().Where(p => p.id == item.id).ToList();
                if ((list == null) || (list.Count == 0))
                {
                    UIMessageBox.Show("没有要保存的模板数据。", "系统提示", UIStyle.Black, UIMessageBoxButtons.OK);
                    return;
                }
                string value = "";
                this.InputStringDialog(ref value, true, "请输入模板名称：", true);
                if (string.IsNullOrEmpty(value.Trim())) return;
                var ftemplate = new FMTemplate();
                ftemplate.typeName = value;
                ftemplate.data = list;
                string msg = "";
                //var bl = new PosRemoteServices(AppConstVars.sUrl).DoCreateTemplate(ftemplate, AppConstVars.sysUser.ccessToken, ref msg);
                //if (!bl) UIMessageBox.Show("保存失败。", "系统提示", UIStyle.Black, UIMessageBoxButtons.OK);
                //else UIMessageBox.Show("保存成功", "系统提示", UIStyle.Blue, UIMessageBoxButtons.OK);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void Detail_OnModifyItemClick(object sender, System.EventArgs e)
        {
            try
            {
                corecmsprintbilltemplate printbilltemplate = (corecmsprintbilltemplate)sender;             
                if (printbilltemplate == null)
                {
                    UIMessageBox.Show("模板不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                int sbilltypeId = printbilltemplate.billtypeId;
                int sfoodPrintType = printbilltemplate.foodPrintType;
                PrinterUnits.ShowPrintBillSet(null, printbilltemplate, 1, sbilltypeId, sfoodPrintType);

                GetTemplatDetail(typeId);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错:", UIStyle.Orange, UIMessageBoxButtons.OK);
            }
        }

        private void Detail_OnModifyReportClick(object sender, System.EventArgs e)
        {
            try
            {
                corecmsprintbilltemplate printbilltemplate = (corecmsprintbilltemplate)sender;
                if (printbilltemplate == null)
                {
                    UIMessageBox.Show("模板不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }

                new ReportServices().SetDesignReport(printbilltemplate);                
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "系统出错:", UIStyle.Orange, UIMessageBoxButtons.OK);
            }
        }

        private void frmPrintTemplate_Load(object sender, System.EventArgs e)
        {
            LoadPrintScheme();
            tvTemplate.ExpandAll();            
            if (!AppConstVars.isAdminUser) btnSaveTemplate.Visible = false;
        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void tvBilltype_AfterSelect(object sender, TreeViewEventArgs e)
        {
            typeId = CommFunc.ConvertToInt32(e.Node.Tag);
            GetTemplatDetail(typeId);
        }

        private void btnEditPrintBilltype_Click(object sender, EventArgs e)
        {
            if (typeId < 1) { UIMessageBox.Show("请选择需要修改的数据", "系统提示", UIStyle.Black, UIMessageBoxButtons.OK); return; }
            corecmsprintbilltemplate template = new corecmsprintbilltemplateServices().SelectById(typeId);
            frmPrintTemplateInfo frm = new frmPrintTemplateInfo(template);
            frm.ShowDialog();
            frm.Dispose();
        }
                
        private void btnAddbilltemplate_Click(object sender, EventArgs e)
        {
            if (typeId < 1) { UIMessageBox.Show("请选择需要新增的模板类型", "系统提示", UIStyle.Blue, UIMessageBoxButtons.OK); return; }
            PrinterUnits.ShowPrintBillSet(null, null, 0, typeId, 0);
            GetTemplatDetail(typeId);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            var frm = new frmInputNumber(0, "清空模板口令");
            frm.IsNumber = false;
            frm.txtNumber.PasswordChar = '*';
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string password = CommFunc.ConvertToString(frm.txtNumber.Text);
                if (password != DateTime.Now.ToString("yyyyMMdd"))
                {
                    UIMessageBox.Show("输入的口令错误。", "系统提示", UIStyle.Black, UIMessageBoxButtons.OK);
                }
                else
                {
                    //new corecmsfoodorderingmasterServices().Update(orderingMaster);
                    if (!ShowAskDialog("确定要清空所有打印格式模板吗？（清空后所有打印格式设置将无法恢复，请慎重操作。）")) return;
                }
            }
            frm.Dispose();
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            GetPrintTemplatePool(null);
        }

        private void GetPrintTemplatePool(corecmsprintbilltemplate printbilltemplate)
        {
            var frm = new frmPrintTemplatePool(printbilltemplate);
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnSaveTemplate_Click(object sender, EventArgs e)
        {
            var templateIds = new corecmsprintschemedetailServices().AsQueryable()
                .Where(p => p.selectedFlag == true).Select(p => p.templateId).ToList();

            var list = new corecmsprintbilltemplateServices().AsQueryable().Where(p => templateIds.Contains(p.id)).ToList();
            if ((list == null) || (list.Count == 0))
            {
                UIMessageBox.Show("没有要保存的模板数据。", "系统提示", UIStyle.Black, UIMessageBoxButtons.OK);
                return;
            }
            string value = "";
            this.InputStringDialog(ref value, true, "请输入模板名称：", true);
            if (string.IsNullOrEmpty(value.Trim())) return;
            var ftemplate = new FMTemplate();
            ftemplate.typeName = value;
            ftemplate.data = list;
            string msg = "";
            var bl = new ApiRemoteServices().DoCreateTemplate(ftemplate, ref msg);
            if (!bl) UIMessageBox.Show("保存失败。", "系统提示", UIStyle.Black, UIMessageBoxButtons.OK);
        }
    }
}
